<template>
    <div id="ticket">
        <div>
            <el-card class="box-card">
                <el-row>
                    <el-col :span="3"> 
                    <el-input
                        placeholder="请输入景区名称"
                        v-model="scenicName"
                        clearable>
                        </el-input>
                    </el-col>
                    
                    <el-col :span="3" :push="2"> 
                    <el-input
                        placeholder="请输入景区票价最低价"
                        v-model="ticketPriceMin"
                        oninput="value=value.replace(/[^0-9]/g,'')"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="1" :push="2" style="text-align: center;">至</el-col>
                    <el-col :span="3" :push="2">
                        <el-input
                        placeholder="请输入景区票价最高价"
                        v-model="ticketPriceMax"
                        oninput="value=value.replace(/[^0-9]/g,'')"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="2" :push="2" :offset="1"><el-button icon="el-icon-search" @click="getTicketByPage" circle></el-button></el-col>
                    <el-col :span="2" :push="2"><el-button type="primary" @click="saveTicketdialog" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-table
                            v-loading="loading"
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="scenicName"
                            label="景区名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="ticketPrice"
                            label="票价"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="tickets"
                            label="一共票数"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="surplusTickets"
                            label="剩余票数"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="openTime"
                            label="开放时间"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="closeTime"
                            label="关闭时间"
                            >
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleClick(scope.row)" type="text" size="small" >查看</el-button>
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>、
                                <el-button @click="deleteTicket(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                    </el-pagination>          
                </el-row>
            </el-card>
                <!-- 门票新增弹窗 -->
                <el-dialog title="新增景区门票" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
                    <el-form :model="productForm" :rules="rules" ref="productForm">
                        <el-form-item label="景区名称" :label-width="formLabelWidth" prop="scenicId">
                            <el-select
                                v-model="productForm.provinceId"
                                placeholder="请选择省份"
                                @change="changeProvince()"
                                >
                                <el-option
                                    v-for="item in one"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getCity()"
                                />
                            </el-select>
                            <el-select
                                v-model="productForm.cityId"
                                placeholder="请选择城市"
                                :disabled="cityDis"
                                @change="changeCity()"
                                >
                                <el-option
                                    v-for="item in two"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getScenic()"
                                />
                            </el-select>
                            <el-select
                                v-model="productForm.scenicId"
                                placeholder="请选择景区"
                                :disabled="scenicDis"
                                >
                                <el-option
                                    v-for="item in three"
                                    :key="item.id"
                                    :label="item.scenicName"
                                    :value="item.id"
                                    clearable
                                    @click.native="getScenicName(item.scenicName,item.price,item.id)"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="景区门票" :label-width="formLabelWidth" prop="tickets">
                            <el-input v-model="productForm.tickets" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="开放时间" :label-width="formLabelWidth" prop="openTime">
                        <el-date-picker
                            v-model="productForm.openTime"
                            type="datetime"
                            placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="关闭时间" :label-width="formLabelWidth" prop="closeTime">
                        <el-date-picker
                            v-model="productForm.closeTime"
                            type="datetime"
                            placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item> 
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button  @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="saveTicket('productForm')">确 定</el-button>
                    </div>
                </el-dialog>
                <!-- 门票查看弹窗 -->
                <el-dialog title="查看详情" :visible.sync="dialogFormVisibleDatil">
                    <el-form :model="productFormList" >
                        <el-form-item label="景区名称" :label-width="formLabelWidth" >
                            <el-select
                                v-model="productFormList.provinceId"
                                placeholder="请选择省份"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in one"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getCity()"
                                />
                            </el-select>
                            <el-select
                                v-model="productFormList.cityId"
                                placeholder="请选择城市"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in two"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getScenic()"
                                />

                            </el-select>
                            <el-select
                                v-model="productFormList.scenicId"
                                placeholder="请选择景区"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in three"
                                    :key="item.id"
                                    :label="item.scenicName"
                                    :value="item.id"
                                    @click.native="getScenicName(item.scenicName,item.price,item.id)"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="景区门票" :label-width="formLabelWidth">
                            <el-input v-model="productFormList.tickets" autocomplete="off" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="景区剩余门票" :label-width="formLabelWidth">
                            <el-input v-model="productFormList.surplusTickets" autocomplete="off" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="开放时间" :label-width="formLabelWidth">
                            <el-date-picker
                                v-model="productFormList.openTime"
                                type="datetime"
                                :disabled="true"
                                placeholder="选择日期时间"
                                >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="关闭时间" :label-width="formLabelWidth" prop="closeTime">
                            <el-date-picker
                                v-model="productFormList.closeTime"
                                type="datetime"
                                :disabled="true"
                                placeholder="选择日期时间"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisibleDatil = false">关闭</el-button>
                    </div>
                </el-dialog>
                <!-- 门票修改弹窗 -->
                <el-dialog title="景区门票管理" :visible.sync="dialogFormVisibleUpdate">
                    <el-form :model="productFormEdit" :rules="rules1" ref="productFormEdit" >
                        <el-form-item label="景区名称" :label-width="formLabelWidth" >
                            <el-select
                                v-model="productFormEdit.provinceId"
                                placeholder="请选择省份"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in one"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getCity()"
                                />
                            </el-select>
                            <el-select
                                v-model="productFormEdit.cityId"
                                placeholder="请选择城市"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in two"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    @click.native="getScenic()"
                                />
                            </el-select>
                            <el-select
                                v-model="productFormEdit.scenicId"
                                placeholder="请选择景区"
                                :disabled="true"
                                >
                                <el-option
                                    v-for="item in three"
                                    :key="item.id"
                                    :label="item.scenicName"
                                    :value="item.id"
                                    @click.native="getScenicName(item.scenicName,item.price,item.id)"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="景区门票" :label-width="formLabelWidth">
                            <el-input v-model="productFormEdit.tickets" autocomplete="off" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="景区剩余门票" :label-width="formLabelWidth">
                            <el-input v-model="productFormEdit.surplusTickets" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="开放时间" :label-width="formLabelWidth">
                            <el-date-picker
                                v-model="productFormEdit.openTime"
                                type="datetime"
                                placeholder="选择日期时间"
                                >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="关闭时间" :label-width="formLabelWidth" prop="closeTime">
                            <el-date-picker
                                v-model="productFormEdit.closeTime"
                                type="datetime"
                                placeholder="选择日期时间"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                        <el-button type="primary" @click="updateTicket('productFormEdit')">确 定</el-button>
                    </div>
                </el-dialog>
        </div>
    </div>
</template>
<script>
const axios = require('axios');
export default {
   name: 'ticket',
        data(){
            //新增弹窗检查景区名称是否为空
            var validatePass2 = (rule, value, callback) => {
                if(value===''){
                        callback(new Error('请选择景区'));
                }
                else if(value!==''){
                //新增弹窗检查景区是否重复
                axios.get("http://127.0.0.1:8082/ticket/getScenicName?pid="+this.scenicId).then(res=>{
                        this.aid= res.data.obj
                        this.aid.forEach((item)=>{
                            this.b=item.scenicId
                        })
                        if (value===this.b) {
                            callback(new Error('景区已录入'));
                        } else {
                            callback();
                        }
                    })
                    }
                };
            //新增弹窗检查门票数是否为空
            var tickets = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入票数'));
                } else {
                	callback();
                }
            };
            //新增弹窗检查开放时间是否为空
            var openTime = (rule, value, callback) => {
                if (value === '') {
                	callback(new Error('请选择开放时间'));
                } else {
                	callback();
                }
            };
            //新增弹窗检查关闭时间是否为空和比较是否比开放时间早
            var closeTime = (rule, value, callback) => {
                if (value === '') {
                	callback(new Error('请选择关闭时间'));
                }else if(value<this.productForm.openTime){
                	callback(new Error("关闭时间需晚于开放时间!"));
                } else {
                	callback();
                }
            };

            //修改方法检查关闭时间是否比开放时间早
            var EditcloseTime= (rule, value, callback) => {
                if(value<this.productFormEdit.openTime){
                	callback(new Error("关闭时间需晚于开放时间!"));
                } else {
                	callback();
                }
            };
            return {
                ticketPriceMin:"",//模糊查最低票价
                ticketPriceMax:'',//模糊查最高票价
                // 新增门票景区下拉状态
                scenicDis: true,
                // 新增门票城市下拉状态
                cityDis: true,
                loading:true,  //初始化加载效果
                aid:[], //新增校验查看是否重复录入的景区集合
                b:'', //新增校验存放的id
                scenicName:"",//存放模糊查的值
                productData: [],//分页全查结果集合
                dialogFormVisible: false,//新增弹框true弹出
                dialogFormVisibleDatil:false,//查看弹框true弹出
                dialogFormVisibleUpdate:false,//修改弹框true弹出
                productForm: {// 新增时使用到的form对象
                    id:"",
                    provinceId:"",
                    cityId:"",
                    ticketsSold:"",
                    surplusTickets:"",
                    scenicId:"",
                    tickets:"",
                    ticketPrice:"",
                    scenicName:"",
                    openTime:"",
                    closeTime:""
                },
                productFormList:{//查看时使用到的form对象
                    id:"",
                    provinceId:"",
                    cityId:"",
                    ticketsSold:"",
                    surplusTickets:"",
                    scenicId:"",
                    tickets:"",
                    ticketPrice:"",
                    scenicName:"",
                    openTime:"",
                    closeTime:"",
                },
                productFormEdit:{// 修改时使用到的form对象
                    id:"",
                    provinceId:"",
                    cityId:"",
                    ticketsSold:"",
                    surplusTickets:"",
                    scenicId:"",
                    tickets:"",
                    ticketPrice:"",
                    scenicName:"",
                    openTime:"",
                    closeTime:"",
                    cityName:""
                    },
                formLabelWidth: '120px',
                currentPage4: 1,//分页当前选中页
                page:{
                    pageSize:10,//条数
                    pageNum:1,//页数
                    total:0
                    },
                    tatal:0,
                    filterText: '',
                    data: [],
                    options: [],
                    defaultProps: {
                    children: 'childs',
                    label: 'departmentName'
                    },
                    one:[],
                    pid:0,
                    provinceId:'',
                    cityId:'',
                    two:[],
                    three:[],
                    four:[],
                    name: '',
                    ticketPrice:'',
                    scenicId:'',
                cityName:'',
                //自定义校验规则
                //新增门票校验规则
                    rules: {
                    scenicId: [
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    tickets:[
                        { validator: tickets, trigger: 'blur' }
                    ],
                    openTime:[
                        { validator: openTime, trigger: 'blur' }
                    ],
                    closeTime:[
                        { validator: closeTime, trigger: 'blur' }
                    ]
                    },
                //修改门票校验规则
                rules1: {
                    closeTime:[
                        { validator: EditcloseTime, trigger: 'blur' }
                    ]
                },
                openTime:""
            }
        },
          //初始化加载
            mounted(){
                this.getTicketByPage()//分页全查+模糊查（景区名称）
                this.getProvince()
             }, 
            methods:{
                changeProvince () {
                    this.cityDis = false
                },
                changeCity () {
                    this.scenicDis = false
                },
                //新增清空值
                handleClose(formName) {
                    this.cityDis = true
                    this.scenicDis = true
                    this.productForm.provinceId=''
                    this.productForm.cityId=''
                    this.productForm.scenicId=''
                    this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
                    },
                //时间重新定义格式//编辑时回显用该方法this.StrToGMT('2020-10-27 09:23')转换成Tue Oct 27 2020 09:23:00 GMT+0800 
                StrToGMT(time) {
                    let GMT = new Date(time);
                    return GMT;
                  },
                //时间重新定义格式//编辑时回显用该方法this.dateValue Oct 27 2020 09:23:00 GMT+0800 转换成('2020-10-27 09:23')
                dateValue(time) {
                    let d = new Date(time);
                    const resDate =
                      d.getFullYear() +
                      "-" +
                      this.monthOrDay(d.getMonth() + 1) +
                      "-" +
                      this.monthOrDay(d.getDate()) +
                      " " +
                      this.monthOrDay(d.getHours()) +
                      ":" +
                      this.monthOrDay(d.getMinutes());
                    return resDate;
                  },
                //查询省份（三级联动）(一级)
                getProvince(){
                    axios.get('http://127.0.0.1:8082/ticket/getProvinceAllList?pid=' + this.pid)
                    .then((res) => {
                        this.one = res.data.obj
                    })
                },
                //查询城市（三级联动）（二级）
                getCity(){
                    this.productForm.cityId=''
                    this.productForm.scenicId=''
                    axios.get('http://127.0.0.1:8082/ticket/getCityAllList?provinceId=' + this.productForm.provinceId)
                    .then((res) => {
                        this.two = res.data.obj
                    })
                },
                //查询景区（三级联动）（三级）
                getScenic(){
                    axios.get('http://127.0.0.1:8082/ticket/getScenicAllList?cityId=' + this.productForm.cityId)
                    .then((res) => {
                        this.three = res.data.obj
                    })
                },
                //赋值景区名称、景区价格
                getScenicName(scenicName,price,id){
                    this.name = scenicName
                    this.ticketPrice=price
                    this.scenicId=id
                },
                handleRemove(file, fileList) {
                        console.log(file, fileList);
                },
                handlePreview(file) {
                    console.log(file);
                },
                // 分页
                handleSizeChange(ps) {
                    this.page.pageSize=ps;
                    this.getTicketByPage()
                    console.log(`每页 ${val} 条`);
                },
                handleCurrentChange(pn) {
                    this.page.pageNum=pn;
                    this.getTicketByPage()
                
                },
              //门票分页查+模糊查（景区名称）
                getTicketByPage () {
                  axios.get('http://127.0.0.1:8082/ticket/getTicketByPage', {
                      params: {
                        scenicName: this.scenicName,
                        pageSize: this.page.pageSize,
                        pageNum: this.page.pageNum,
                        ticketPrice : this.ticketPriceMin,
                        ticketPrice1 : this.ticketPriceMax, 
                      }
                    })
                    .then((res) => {
                      this.loading=false
                      this.productData = res.data.content
                      this.page.total = res.data.total
                    })
                },
                //新增门票
                saveTicket(formName){ 
                    var formdata = new FormData();
                    formdata.set("provinceId",this.productForm.provinceId)
                    formdata.set("cityId",this.productForm.cityId)
                    formdata.set("scenicId",this.productForm.scenicId)
                    formdata.set("scenicName",this.name)
                    formdata.set("ticketPrice",this.ticketPrice)
                    formdata.set("tickets",this.productForm.tickets)
                    formdata.set("openTime",this.productForm.openTime)
                    formdata.set("closeTime",this.productForm.closeTime)
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            axios.post("http://127.0.0.1:8082/ticket/saveTicket",formdata).
                            then(res => {
                              if(res.data.obj>0){
                                  this.message("恭喜你，保存数据成功！","success")
                                  this.dialogFormVisible = false
                                  this.imageUrl=""
                                  this.imageFile=File
                                  this.productForm={
                                      provinceId:"",
                                      cityId:"",
                                      ticketsSold:"",
                                      surplusTickets:"",
                                      scenicId:"",
                                      tickets:"",
                                      ticketPrice:"",
                                      scenicName:""
                                  }
                                  this.getTicketByPage()
                              }else{
                                  this.message("对不起，保存失败！","warning")
                              }
                          }).catch(error => {
                              this.$message.error('服务器崩溃了，请稍后再尝试使用！');
                          })
                        } else {
                          return false;
                        }
                    });
                },
                //修改门票
                updateTicket(formName){
					var formdata = new FormData();
					formdata.set("id",this.productFormEdit.id)
					formdata.set("surplusTickets",this.productFormEdit.surplusTickets)
					formdata.set("ticketsSold",this.productFormEdit.ticketsSold)
					formdata.set("tickets",this.productFormEdit.tickets)
					formdata.set("openTime",this.productFormEdit.openTime)
					formdata.set("closeTime",this.productFormEdit.closeTime)
					formdata.set("provinceId",this.productFormEdit.provinceId)
					formdata.set("scenicId",this.productFormEdit.scenicId)
					formdata.set("cityId",this.productFormEdit.cityId)
					this.$refs[formName].validate((valid) => {
						if (valid) {
							axios.put("http://127.0.0.1:8082/ticket/updateTicket",formdata)
							.then(res=>{
								if(res.data.code==='200'){
								this.message("恭喜你，修改数据成功！","success")
										this.dialogFormVisibleUpdate = false
										this.imageUrl = ''
										this.imageFile=File
										this.productFormEdit={
											provinceId:"",
											cityId:"",
											ticketsSold:"",
											surplusTickets:"",
											scenicId:"",
											tickets:"",
											ticketPrice:"",
											scenicName:""
										}
										this.getTicketByPage()// 重新渲染数据列表
								}else{
										this.message("对不起，修改失败！","warning")
									}
								}).catch(error => {
									this.$message.error('服务器崩溃了，请稍后再尝试使用！');
							})
						}else {
							return false;
							}
					}); 
                },
                //删除门票
                deleteTicket(row){
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }//删除提示框
                    ).then(() => {
                        axios.delete("http://127.0.0.1:8082/ticket/deleteTicket?id="+row.id)
                    .then(res =>{
                        if(res.data.code==='200' ){
                          this.message("恭喜你，删除成功！","success")
                          this.getTicketByPage()
                        }else{
                            this.message('删除失败','warning')
                        }
                    }).catch(error =>{
                           alert(error)
                    })
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                    });
                },
                //消息提示框
                message(message,type){
                    this.$message({
                    message:message,
                    type: type
                    });
                },
                //点击查看按钮回显值
                handleClick(row){
                    this.dialogFormVisibleDatil = true
                    this.productFormList =row
                    this.getCity()
                    this.getScenic()
                },
                //点击编辑按钮回显值
                handleUpdate(row){
                    this.dialogFormVisibleUpdate=true
                    this.productFormEdit.ticketsSold=row.ticketsSold
                    this.productFormEdit.surplusTickets=row.surplusTickets
                    this.productFormEdit.tickets=row.tickets
                    this.productFormEdit.provinceId=row.provinceId
                    this.productFormEdit.cityId=row.cityId
                    this.productFormEdit.scenicId=row.scenicId
                    this.productFormEdit.id=row.id
					this.$set(this.productFormEdit, "openTime", new Date())
					this.$set(this.productFormEdit, "closeTime", new Date())
                    this.productFormEdit.openTime=this.StrToGMT(row.openTime)
                    this.productFormEdit.closeTime=this.StrToGMT(row.closeTime)
                    this.getCity()
                    this.getScenic()
                },
                //新增门票按钮弹框
                saveTicketdialog(){
                  this.dialogFormVisible = true
                }
            },
}
</script>
<style>
/**
* 附件上传样式
*/
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.el-icon-arrow-down {
    font-size: 12px;
}
.box-card {
    height: 100%;
}
</style>